package com.yugao.fintech.antelope.infra.job.utils;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.yugao.fintech.antelope.infra.job.constants.JobCons;
import com.yugao.fintech.antelope.infra.job.model.entity.JobInfo;
import com.yugao.fintech.antelope.infra.job.model.entity.JobLog;
import com.yugao.fintech.antelope.infra.job.service.IJobLogService;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.antelope.base.tenant.core.utils.TenantUtils;
import com.yugao.fintech.framework.assistant.utils.ExceptionUtil;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import com.yugao.fintech.framework.core.utils.SpringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * 抽象quartz调用
 *

 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static final TransmittableThreadLocal<Date> threadLocal = new TransmittableThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) {
        JobInfo jobInfo = new JobInfo();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(JobCons.TASK_PROPERTIES), jobInfo);
        TenantUtils.execute(jobInfo.getTenantId(), () -> {
            try {
                before(context, jobInfo);
                doExecute(context, jobInfo);
                after(context, jobInfo, null);
            } catch (Exception e) {
                log.error("任务执行异常  - ：", e);
                after(context, jobInfo, e);
            }
        });
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param jobInfo  系统计划任务
     */
    protected void before(JobExecutionContext context, JobInfo jobInfo) {
        threadLocal.set(new Date());
        TenantContextHolder.get().setTenantId(jobInfo.getTenantId());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param jobInfo  系统计划任务
     */
    protected void after(JobExecutionContext context, JobInfo jobInfo, Exception e) {
        Date startTime = threadLocal.get();
        threadLocal.remove();

        final JobLog jobLog = new JobLog();
        jobLog.setJobName(jobInfo.getJobName());
        jobLog.setJobGroup(jobInfo.getJobGroup());
        jobLog.setInvokeTarget(jobInfo.getInvokeTarget());
        jobLog.setStartTime(startTime);
        jobLog.setStopTime(new Date());
        long runMs = jobLog.getStopTime().getTime() - jobLog.getStartTime().getTime();
        jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            jobLog.setStatus("1");
            String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
            jobLog.setExceptionInfo(errorMsg);
        } else {
            jobLog.setStatus("0");
        }
        jobLog.setJobId(jobInfo.getId());

        // 写入数据库当中
        SpringUtils.getBean(IJobLogService.class).save(jobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param jobInfo  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, JobInfo jobInfo) throws Exception;
}
